package com.lhkj.ct.meta.modules.patient.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.lhkj.ct.base.exception.ValidatedException;
import com.lhkj.ct.base.utils.ShiroUtil;
import com.lhkj.ct.meta.modules.patient.mapper.PatCardRelationMapper;
import com.lhkj.ct.meta.modules.patient.model.entity.TblPatCardRelation;
import com.lhkj.ct.meta.modules.patient.service.PatCardRelationService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 用户绑定就诊卡 服务实现类
 * </p>
 *
 * @author jobob
 * @since 2023-12-15
 */
@Service
public class PatCardRelationServiceImpl extends ServiceImpl<PatCardRelationMapper, TblPatCardRelation> implements PatCardRelationService {

    @Override
    public List<TblPatCardRelation> selectByUser() {
        return getBaseMapper().selectByUser(ShiroUtil.getAuthUserInfo().getIdentifier(), ShiroUtil.getAuthUserInfo().getUserId());
    }

    @Override
    public boolean createDefaultCard(TblPatCardRelation patCardRelation) {
        TblPatCardRelation defaultPatCard = getBaseMapper().selectOne(new LambdaQueryWrapper<TblPatCardRelation>()
                .eq(TblPatCardRelation::getIdentifier, patCardRelation.getIdentifier())
                .eq(TblPatCardRelation::getIsDefault, true)
        );
        // 修改默认就诊卡
        if (null != defaultPatCard) {
            defaultPatCard.setPatId(patCardRelation.getPatId());
            defaultPatCard.setPatCardNo(patCardRelation.getPatCardNo());
            defaultPatCard.setCreateTime(LocalDateTime.now());
            return SqlHelper.retBool(getBaseMapper().updateById(defaultPatCard));
        }else{
            return  SqlHelper.retBool(getBaseMapper().insert(patCardRelation));
        }
    }

    @Override
    public boolean bindPatCard(TblPatCardRelation patCardRelation, boolean isIgnoreException) {
        // 查看是否已存在默认就诊卡
        Long count = getBaseMapper().selectCount(new LambdaQueryWrapper<TblPatCardRelation>()
                .eq(TblPatCardRelation::getIdentifier, patCardRelation.getIdentifier())
                .eq(TblPatCardRelation::getPatCardNo, patCardRelation.getPatCardNo())
        );
        if (!isIgnoreException && count > 0) {
            throw new ValidatedException(String.format("已绑定该就诊卡号[%s]，请勿重复绑定！", patCardRelation.getPatCardNo()));
        }
        return count > 0 || SqlHelper.retBool(getBaseMapper().insert(patCardRelation));
    }
}
